package com.chengyu.core.service.services.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.chengyu.core.domain.enums.ServicesEnums;
import com.chengyu.core.domain.form.ServicesPublishGroupForm;
import com.chengyu.core.mapper.PmsServicesGroupMapper;
import com.chengyu.core.mapper.PmsServicesMapper;
import com.chengyu.core.model.PmsServices;
import com.chengyu.core.model.PmsServicesExample;
import com.chengyu.core.model.PmsServicesGroup;
import com.chengyu.core.model.UmsShop;
import com.chengyu.core.service.services.ServicesGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ServicesGroupServiceImpl implements ServicesGroupService {

	@Autowired
	private PmsServicesMapper servicesMapper;
	@Autowired
	private PmsServicesGroupMapper servicesGroupMapper;

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void addGroupServices(UmsShop shop, ServicesPublishGroupForm publishForm) {
		PmsServices updateServices = new PmsServices();
		updateServices.setId(publishForm.getId());
		updateServices.setType(ServicesEnums.ServicesType.GROUP_GOODS.getValue());
		updateServices.setGroupType(publishForm.getGroupType());
		updateServices.setGroupNum(publishForm.getGroupNum());
		updateServices.setGroupLimitBuy(publishForm.getGroupLimitBuy());
		updateServices.setGroupLimitHours(publishForm.getGroupLimitHours());
		updateServices.setGroupSingleBuy(publishForm.getGroupSingleBuy());
		servicesMapper.updateByPrimaryKeySelective(updateServices);

		//团购
		if(CollectionUtil.isNotEmpty(publishForm.getGroupList())){
			for(PmsServicesGroup group : publishForm.getGroupList()){
				group.setServicesId(publishForm.getId());
				if(group.getId() == null){
					servicesGroupMapper.insertSelective(group);
				}else{
					servicesGroupMapper.updateByPrimaryKeySelective(group);
				}
			}
		}
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void deleteGroup(List<Integer> servicesIdList) {
		PmsServicesExample example = new PmsServicesExample();
		example.createCriteria().andIdIn(servicesIdList);

		PmsServices updateServices = new PmsServices();
		updateServices.setType(ServicesEnums.ServicesType.NORMAL_GOODS.getValue());
		servicesMapper.updateByExampleSelective(updateServices, example);
	}
}